package com.zenchn.service.impl;

import com.zenchn.dao.TSysOauthTokenMapper;
import com.zenchn.dynamic.TSysOauthTokenDynamicMapper;
import com.zenchn.generic.GenericDao;
import com.zenchn.generic.GenericServiceImpl;
import com.zenchn.model.TSysOauthToken;
import com.zenchn.model.TSysOauthTokenExample;
import com.zenchn.service.OauthTokenService;
import javax.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import static org.mybatis.dynamic.sql.SqlBuilder.*;
import static com.zenchn.dynamic.TSysOauthTokenDynamicSqlSupport.*;
/**
 * 授权令牌 业务实现类
 *
 * @author dingxinfa
 * @date 2020-04-16
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class OauthTokenServiceImpl extends GenericServiceImpl<TSysOauthToken, String, TSysOauthTokenExample> implements OauthTokenService {
	
	@Resource
	private TSysOauthTokenMapper oauthTokenMapper;

	@Resource
	private TSysOauthTokenDynamicMapper oauthTokenDynamicMapper;

	@Override
	public GenericDao<TSysOauthToken, String, TSysOauthTokenExample> getDao() {
		return oauthTokenMapper;
	}

	@Override
	public TSysOauthToken refreshAuthentication(String clientId, String refreshToken) {
		TSysOauthTokenExample example=new TSysOauthTokenExample();
		example.createCriteria().andClientIdEqualTo(clientId).andRefreshTokenEqualTo(refreshToken);
		List<TSysOauthToken> list=oauthTokenMapper.selectByExample(example);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	//@Cacheable(value = "monitor-early-warning:cache:2hours", key="'accessToken:'+#accessToken",unless="#result == null")
	public TSysOauthToken tokenAuthentication(String accessToken) {
		TSysOauthTokenExample example=new TSysOauthTokenExample();
		example.createCriteria().andAccessTokenEqualTo(accessToken);
		List<TSysOauthToken> list=oauthTokenMapper.selectByExample(example);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	//@CacheEvict(value="monitor-early-warning:cache:2hours",key="'accessToken:'+#accessToken")
	public void deleteByAccessToken(String accessToken) {
		TSysOauthTokenExample example=new TSysOauthTokenExample();
		example.createCriteria().andAccessTokenEqualTo(accessToken);
		oauthTokenMapper.deleteByExample(example);
	}

	@Override
	public TSysOauthToken selectByClientIdAndAccountId(String clientId, String accountId) {
		TSysOauthTokenExample example=new TSysOauthTokenExample();
		example.createCriteria().andClientIdEqualTo(clientId).andAccountIdEqualTo(accountId);
		List<TSysOauthToken> list=oauthTokenMapper.selectByExample(example);
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}


}
